package com.hrzyit.whistle.im.util

import android.content.Context
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow


/**
 */
class PopupWindowFactory
/**
 * @param mContext 上下文
 * @param view PopupWindow显示的布局文件
 * @param width PopupWindow的宽
 * @param height PopupWindow的高
 */
@JvmOverloads constructor(
    mContext: Context,
    view: View,
    width: Int = ViewGroup.LayoutParams.WRAP_CONTENT,
    height: Int = ViewGroup.LayoutParams.WRAP_CONTENT
) {

    private var mContext: Context? = null

    var popupWindow: PopupWindow? = null
        private set

    init {
        init(mContext, view, width, height)
    }


    private fun init(mContext: Context, view: View, width: Int, height: Int) {
        this.mContext = mContext

        //下面这两个必须有！！
        view.isFocusable = true
        view.isFocusableInTouchMode = true

        // PopupWindow(布局，宽度，高度)
        popupWindow = PopupWindow(view, width, height, true)
        popupWindow!!.isFocusable = true

        // 重写onKeyListener,按返回键消失
        view.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                popupWindow!!.dismiss()
                return@OnKeyListener true
            }
            false
        })

        //点击其他地方消失
        view.setOnTouchListener(View.OnTouchListener { v, event ->
            if (popupWindow != null && popupWindow!!.isShowing) {
                popupWindow!!.dismiss()
                return@OnTouchListener true
            }
            false
        })


    }


    /**
     * 以触发弹出窗的view为基准，出现在view的内部上面，弹出的pop_view左上角正对view的左上角
     * @param parent view
     * @param gravity 在view的什么位置 Gravity.CENTER、Gravity.TOP......
     * @param x 与控件的x坐标距离
     * @param y 与控件的y坐标距离
     */
    fun showAtLocation(parent: View, gravity: Int, x: Int, y: Int) {

        if (popupWindow!!.isShowing) {
            return
        }
        popupWindow!!.showAtLocation(parent, gravity, x, y)

    }

    /**
     * 以触发弹出窗的view为基准，出现在view的正下方，弹出的pop_view左上角正对view的左下角
     * @param anchor view
     * @param xoff 与view的x坐标距离
     * @param yoff 与view的y坐标距离
     */
    @JvmOverloads
    fun showAsDropDown(anchor: View, xoff: Int = 0, yoff: Int = 0) {
        if (popupWindow!!.isShowing) {
            return
        }

        popupWindow!!.showAsDropDown(anchor, xoff, yoff)
    }

    /**
     * 隐藏PopupWindow
     */
    fun dismiss() {
        if (popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        }
    }

}
/**
 * @param mContext 上下文
 * @param view PopupWindow显示的布局文件
 */
/**
 * 以触发弹出窗的view为基准，出现在view的正下方，弹出的pop_view左上角正对view的左下角
 * @param anchor view
 */
